import { MigrationInterface, QueryRunner, Table, TableForeignKey } from 'typeorm';

export class AddPaymentTables1703000000002 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    // 创建payments表
    await queryRunner.createTable(
      new Table({
        name: 'payments',
        columns: [
          {
            name: 'id',
            type: 'varchar',
            length: '36',
            isPrimary: true,
            generationStrategy: 'uuid',
            default: '(UUID())',
          },
          {
            name: 'stripe_payment_intent_id',
            type: 'varchar',
            length: '255',
            isUnique: true,
          },
          {
            name: 'stripe_customer_id',
            type: 'varchar',
            length: '255',
            isNullable: true,
          },
          {
            name: 'amount',
            type: 'decimal',
            precision: 10,
            scale: 2,
          },
          {
            name: 'currency',
            type: 'varchar',
            length: '3',
          },
          {
            name: 'status',
            type: 'enum',
            enum: ['pending', 'processing', 'succeeded', 'failed', 'canceled', 'requires_action'],
            default: "'pending'",
          },
          {
            name: 'payment_method',
            type: 'varchar',
            length: '255',
            isNullable: true,
          },
          {
            name: 'description',
            type: 'text',
            isNullable: true,
          },
          {
            name: 'metadata',
            type: 'json',
            isNullable: true,
          },
          {
            name: 'user_id',
            type: 'int',
          },
          {
            name: 'created_at',
            type: 'timestamp',
            default: 'CURRENT_TIMESTAMP',
          },
          {
            name: 'updated_at',
            type: 'timestamp',
            default: 'CURRENT_TIMESTAMP',
            onUpdate: 'CURRENT_TIMESTAMP',
          },
        ],
      }),
      true
    );

    // 创建subscriptions表
    await queryRunner.createTable(
      new Table({
        name: 'subscriptions',
        columns: [
          {
            name: 'id',
            type: 'varchar',
            length: '36',
            isPrimary: true,
            generationStrategy: 'uuid',
            default: '(UUID())',
          },
          {
            name: 'stripe_subscription_id',
            type: 'varchar',
            length: '255',
            isUnique: true,
          },
          {
            name: 'stripe_customer_id',
            type: 'varchar',
            length: '255',
          },
          {
            name: 'stripe_price_id',
            type: 'varchar',
            length: '255',
          },
          {
            name: 'status',
            type: 'enum',
            enum: ['incomplete', 'incomplete_expired', 'trialing', 'active', 'past_due', 'canceled', 'unpaid', 'paused'],
            default: "'incomplete'",
          },
          {
            name: 'current_period_start',
            type: 'timestamp',
          },
          {
            name: 'current_period_end',
            type: 'timestamp',
          },
          {
            name: 'trial_start',
            type: 'timestamp',
            isNullable: true,
          },
          {
            name: 'trial_end',
            type: 'timestamp',
            isNullable: true,
          },
          {
            name: 'canceled_at',
            type: 'timestamp',
            isNullable: true,
          },
          {
            name: 'cancel_at_period_end',
            type: 'boolean',
            default: false,
          },
          {
            name: 'metadata',
            type: 'json',
            isNullable: true,
          },
          {
            name: 'user_id',
            type: 'int',
          },
          {
            name: 'created_at',
            type: 'timestamp',
            default: 'CURRENT_TIMESTAMP',
          },
          {
            name: 'updated_at',
            type: 'timestamp',
            default: 'CURRENT_TIMESTAMP',
            onUpdate: 'CURRENT_TIMESTAMP',
          },
        ],
      }),
      true
    );

    // 添加stripe_customer_id字段到users表
    await queryRunner.query(`
      ALTER TABLE users 
      ADD COLUMN stripe_customer_id VARCHAR(255) NULL UNIQUE
    `);

    // 创建外键约束
    await queryRunner.createForeignKey(
      'payments',
      new TableForeignKey({
        columnNames: ['user_id'],
        referencedColumnNames: ['id'],
        referencedTableName: 'users',
        onDelete: 'CASCADE',
      })
    );

    await queryRunner.createForeignKey(
      'subscriptions',
      new TableForeignKey({
        columnNames: ['user_id'],
        referencedColumnNames: ['id'],
        referencedTableName: 'users',
        onDelete: 'CASCADE',
      })
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // 删除外键约束
    const paymentsTable = await queryRunner.getTable('payments');
    const paymentsForeignKey = paymentsTable!.foreignKeys.find(
      (fk) => fk.columnNames.indexOf('user_id') !== -1
    );
    if (paymentsForeignKey) {
      await queryRunner.dropForeignKey('payments', paymentsForeignKey);
    }

    const subscriptionsTable = await queryRunner.getTable('subscriptions');
    const subscriptionsForeignKey = subscriptionsTable!.foreignKeys.find(
      (fk) => fk.columnNames.indexOf('user_id') !== -1
    );
    if (subscriptionsForeignKey) {
      await queryRunner.dropForeignKey('subscriptions', subscriptionsForeignKey);
    }

    // 删除表
    await queryRunner.dropTable('subscriptions');
    await queryRunner.dropTable('payments');

    // 删除users表中的stripe_customer_id字段
    await queryRunner.query(`
      ALTER TABLE users 
      DROP COLUMN stripe_customer_id
    `);
  }
}